package middleware

import (
	"admin-system/internal/models/auth_model"
	"admin-system/internal/service/auth_svc"
	"admin-system/pkg/error_code"
	"admin-system/pkg/response"
	"github.com/gin-gonic/gin"
	"log/slog"
)

// 存放用户角色id
var roleCache = make(map[int64]*auth_model.Role)

// 初始化缓存
func init() {
	// 初始化缓存
	roleCache = make(map[int64]*auth_model.Role)
}

func RbacMiddleware(permissionService *auth_svc.PermissionService) gin.HandlerFunc {
	return func(c *gin.Context) {
		// 获取请求路径
		path := c.Request.URL.Path
		if path == "/api/v1/auth/login" || path == "/api/v1/auth/logout" {
			c.Next()
			return
		}
		// 请求方法
		admin, ok := c.Get("username")
		if !ok {
			c.Abort()
			response.Fail(c, error_code.ErrUnauthorized, "用户未认证")
			return
		}
		if admin == nil {
			c.Abort()
			response.Fail(c, error_code.ErrUnauthorized, "用户未认证")
			return
		}
		roleIdAny, ok := c.Get("role_id")
		if !ok {
			c.Abort()
			response.Fail(c, error_code.ErrUnauthorized, "用户未认证")
			return
		}
		roleId, ok := roleIdAny.(int64)
		if !ok {
			slog.Error("角色ID类型断言失败", "value", roleIdAny)
			c.Abort()
			response.Fail(c, error_code.ErrUnauthorized, "无效的角色ID")
			return
		}

		// 查询用户的权限信息
		permissions, err := permissionService.GetPermission(c, &roleId)
		if err != nil {
			slog.Any("获取权限失败", err)
			c.Abort()
			response.Fail(c, error_code.ErrUnauthorized, "获取权限失败")
			return
		}
		// 获取请求方法
		method := c.Request.Method
		authorized := false
		// 处理角色权限
		for _, p := range permissions {
			if p.Path == path && p.Method == method {
				authorized = true
				break
			}
		}
		if !authorized {
			response.Fail(c, error_code.ErrUnauthorized, "用户无权限")
			c.Abort()
			return
		}
		c.Next()
	}
}
